package tt.dz.appserver.dao.ext;

import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Repository;

import tt.dz.appserver.dao.base.BasisDao;
import tt.dz.appserver.entity.model.user.UserInfo;


/**
 * 用户信息操作Dao
 * @author Administrator
 *
 */
@Repository
public class UserInfoDao extends BasisDao<UserInfo>{

	/**查询用户个数*/
	private static final String FIND_USER_COUNT_BY_PHONE_SQL="select count(*) as count from as_user_info where telephone=? and valid_flag=?";
	
	@Override
	@Caching(evict={
		@CacheEvict(value="userInfo",key="#userInfo.telephone+'phone'"),
		@CacheEvict(value="userInfo",key="#userInfo.user_id+'userId'"),
		@CacheEvict(value="userInfoCount",key="#userInfo.telephone+'phone'")
	})
	public int update(UserInfo userInfo) {
		return super.update(userInfo);
	}
	
	@Override
	@Caching(evict={
		@CacheEvict(value="userInfo",key="#userInfo.telephone+'phone'"),
		@CacheEvict(value="userInfo",key="#userInfo.user_id+'userId'"),
		@CacheEvict(value="userInfoCount",key="#userInfo.telephone+'phone'")
	})
	public int save(UserInfo userInfo) {
		return super.save(userInfo);
	}
	
	/**
	 * 用户是否存在  where validflag=1 and phone={phone}
	 * @param phone
	 * @return
	 */
	@Cacheable(value="userInfoCount",key="#phone+'phone'")
	public boolean userExists(String phone){
		
		List<Map<String,Object>> maps = super.findDataOfMapBySQL(new StringBuffer(FIND_USER_COUNT_BY_PHONE_SQL), null, null, phone, 1);
		
		long count = (long)maps.get(0).get("count");
		//如果数量为0表示没有此用户
		if(count == 0l){
			return false;
		}
		return true;
	}
	
	/**
	 * 查询用户信息
	 * @param phone
	 * @return
	 */
	@Cacheable(value="userInfo",key="#phone+'phone'")
	public UserInfo findUserByPhone(String phone){
	
		//设置查询条件
		UserInfo userInfo = new UserInfo();
		userInfo.setTelephone(phone);
		//查询
		List<UserInfo> userInfos = super.findExample(userInfo);
		if(userInfos.size()>0){
			return userInfos.get(0);
		}
		return null;
	}
	
	/**
	 * 查询用户信息
	 * @param userId
	 * @return
	 */
	@Cacheable(value="userInfo",key="#userId+'userId'")
	public UserInfo findUserByUserId(String userId){

		//设置查询条件
		UserInfo userInfo = new UserInfo();
		userInfo.setUser_id(userId);
		//查询
		List<UserInfo> userInfos = super.findExample(userInfo);
		if(userInfos.size()>0){
			return userInfos.get(0);
		}
		return null;
	}
	/**
	 * 获取所以用户
	 * @param userInfo
	 * @return
	 */
	public List<UserInfo>  getAllUsers(UserInfo userInfo){
		List<UserInfo> userInfos = super.findExample(userInfo);
		return   userInfos;
	}
}






